from PySide2.QtWidgets import QDialog, QPushButton, QVBoxLayout, QLineEdit, QMessageBox, QComboBox, QFormLayout
from PySide2.QtGui import Qt
from tool import dbutil


class UserWidget(QDialog):
    def __init__(self, title, data, callback):
        super().__init__()
        self.title = title
        self.data = data
        self.callback = callback
        self.platforms = dbutil.fetchPlatform(2)

        self.uploader = None
        self.setupUi()
        self.setData(title, data)


    def setupUi(self):

        self.mainLayout = QVBoxLayout(self)

        self.formLayout = QFormLayout()

        self.name = QLineEdit()
        self.pwd = QLineEdit()
        self.number = QLineEdit()

        self.combBox = QComboBox()
        self.combBox.addItems(["%s" % platform["name"]
                              for platform in self.platforms])

        self.addBtn = QPushButton('添加')
        self.addBtn.clicked.connect(self.btnClick)

        self.formLayout.addRow("账号：", self.name)
        self.formLayout.addRow("密码：", self.pwd)
        self.formLayout.addRow("视频数量：", self.number)
        self.formLayout.addRow("平台：", self.combBox)

        self.formLayout.setRowWrapPolicy(QFormLayout.DontWrapRows)
        self.formLayout.setLabelAlignment(Qt.AlignLeft)

        self.mainLayout.addLayout(self.formLayout)
        self.mainLayout.addWidget(self.addBtn)

        self.resize(300, 200)
        self.setWindowModality(Qt.ApplicationModal)        

    def setTitle(self, title):
        self.setWindowTitle(title)

    def setData(self, title, uploader):
        self.uploader = uploader
        self.setWindowTitle(title)
        if uploader == None:
            self.name.setText("")
            self.pwd.setText("")
            self.number.setText("")
            self.addBtn.setText("添加")
        else:
            self.name.setText(uploader.account)
            self.pwd.setText(uploader.pwd)
            self.number.setText(str(uploader.number))
            self.addBtn.setText("修改")
        self.exec_()

    def btnClick(self):
        name = self.name.text()
        pwd = self.pwd.text()
        number = self.number.text()

        platformIndex = self.combBox.currentIndex()
        platform = self.platforms[platformIndex]
        if len(name) == 0 or len(pwd) == 0:
            QMessageBox.warning(self, '', "请输入账号和密码", QMessageBox.Yes)
            return
        if len(number) == 0 or int(number) <= 0:
            QMessageBox.warning(self, '', "请输入>0的值", QMessageBox.Yes)
        
        id = None
        if self.uploader != None:
            id = self.uploader.id
        self.callback(name, pwd, platform, number, id)

        self.close()
